"""
Description:
Author: 月间
Date: 2024-08-13 20:28:46
LastEditTime: 2024-11-24 21:32:52
LastEditors:
"""

# @Version        : 1.0
# @Update Time    : 2024/6/15 23:51
# @File           : event.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
from fastapi import FastAPI
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend

from authx.core.auth_logic import AuthLogic
from src.config import settings
from src.core.custom_auth import CustomAuth
from authx.core.manager import AuthManager
from authx.dao.redis.dao import RedisAuthDao
from src.log import logger
from src.core.sqlalchemy_event import (
    register_sqlalchemy_events,
    remove_sqlalchemy_events,
)
from src.db.db_database import alchemy
from src.db.db_mongodb import AsyncMongoManager
from src.db.db_redis import AsyncRedisTool
from src.db.cache import custom_key_builder
from src.services.cache_service import CacheService
from src.services.task_service import TaskService


async def db_event(app: FastAPI, status: bool):
    """
    关闭数据库连接事件
    :param app:
    :param status: 用于判断是开始还是结束事件，为 True 说明是开始事件，反着关闭事件
    :return:
    """
    if status:
        redis = AsyncRedisTool()
        app.state.redis = redis
        app.state.mongo_manager = AsyncMongoManager()
        # 测试数据库是否连接成功
        register_sqlalchemy_events()
        AuthManager.init(
            dao=RedisAuthDao(redis_client=redis.client), auth_imp=CustomAuth()
        )
        AuthManager.put_logic(AuthLogic())
        logger.info("启动项目事件成功执行！")
        if settings.db.REDIS_DB.REDIS_DB_ENABLE:
            FastAPICache.init(
                RedisBackend(redis.client),
                prefix=settings.cache.REDIS_PREFIX,
                key_builder=custom_key_builder,
            )
        await CacheService.get_dict_data_to_cache()
        await task_init()
    else:
        remove_sqlalchemy_events()
        await app.state.redis.close_pool()
        await app.state.mongo_manager.close_pool()
        logger.info("关闭项目事件成功执行！")


async def task_init():
    """
    初始化定时任务
    :return:
    """
    async with alchemy.with_async_session() as session:
        await TaskService(session=session).init_task()
